package com.xuecheng.search.service.impl;

import com.xuecheng.framework.domain.course.CoursePub;
import com.xuecheng.framework.domain.course.TeachplanMediaPub;
import com.xuecheng.framework.domain.search.CourseSearchParam;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.search.service.EsCourseService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Kidy
 * @date 2020/7/7 13:22
 */
@Service
public class EsCourseServiceImpl implements EsCourseService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Value("${xuecheng.course.soure-field}")
    private String soureFields;

    @Value("${xuecheng.media.soure-field}")
    private String mediaSoureFields;

    @Override
    public QueryResponseResult<CoursePub> list(int page, int size, CourseSearchParam courseSearchParam) {
        if (null == courseSearchParam) {
            courseSearchParam = new CourseSearchParam();
        }
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 16;
        }
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //搜索条件
        if (StringUtils.isNotBlank(courseSearchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders
                    .multiMatchQuery(courseSearchParam.getKeyword(), "name", "description", "teachplan")
                    .minimumShouldMatch("70%")
                    .field("name", 10));
        }

        //过滤条件
        if (StringUtils.isNotBlank(courseSearchParam.getMt())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("mt", courseSearchParam.getMt()));
        }
        if (StringUtils.isNotBlank(courseSearchParam.getSt())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("st", courseSearchParam.getSt()));
        }
        if (StringUtils.isNotBlank(courseSearchParam.getGrade())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("grade", courseSearchParam.getGrade()));
        }

        queryBuilder.withQuery(boolQueryBuilder);

        //分页
        queryBuilder.withPageable(PageRequest.of(page - 1, size));

        //源数据过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(soureFields.split(","), null));

        //高亮
        queryBuilder.withHighlightBuilder(new HighlightBuilder().field("name").preTags("<font class='eslight'>").postTags("</font>"));

        //执行搜索
        SearchHits<CoursePub> search = elasticsearchRestTemplate.search(queryBuilder.build(), CoursePub.class);

        List<SearchHit<CoursePub>> searchHits = search.getSearchHits();

        List<CoursePub> coursePubList = searchHits.stream().map(searchHit -> {
            CoursePub coursePub = searchHit.getContent();
            List<String> name = searchHit.getHighlightField("name");
            if (!CollectionUtils.isEmpty(name)) {
                StringBuffer stringBuffer = new StringBuffer();
                name.forEach(s -> {
                    stringBuffer.append(s);
                });
                coursePub.setName(stringBuffer.toString());
            }
            return coursePub;
        }).collect(Collectors.toList());

        QueryResult queryResult = new QueryResult();
        queryResult.setList(coursePubList);
        queryResult.setTotal(search.getTotalHits());
        return new QueryResponseResult<CoursePub>(CommonCode.SUCCESS, queryResult);
    }

    @Override
    public Map<String, CoursePub> getAll(String id) {
        CoursePub coursePub = elasticsearchRestTemplate.get(id, CoursePub.class);
        //queryBuilder.withSourceFilter(new FetchSourceFilter(soureFields.split(","), null));
        Map<String, CoursePub> map = new HashMap<>();
        map.put(id, coursePub);
        return map;
    }

    @Override
    public QueryResponseResult<TeachplanMediaPub> getMeida(String[] id) {
        //定义自定义查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //设置搜索条件
        queryBuilder.withQuery(QueryBuilders.termsQuery("_id", id));
        //设置过滤源字段
        queryBuilder.withSourceFilter(new FetchSourceFilter(mediaSoureFields.split(","), null));
        //执行搜索
        SearchHits<TeachplanMediaPub> search = elasticsearchRestTemplate.search(queryBuilder.build(), TeachplanMediaPub.class);
        List<SearchHit<TeachplanMediaPub>> searchHits = search.getSearchHits();
        List<TeachplanMediaPub> teachplanMediaPubList = searchHits.stream().map(searchHit -> {
            return searchHit.getContent();
        }).collect(Collectors.toList());
        QueryResult<TeachplanMediaPub> teachplanMediaPubQueryResult = new QueryResult<>();
        teachplanMediaPubQueryResult.setTotal(search.getTotalHits());
        teachplanMediaPubQueryResult.setList(teachplanMediaPubList);
        return new QueryResponseResult<TeachplanMediaPub>(CommonCode.SUCCESS,teachplanMediaPubQueryResult);
    }
}
